import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

const JWT_SECRET = 'jsCheng'; // 在实际生产环境中应该使用环境变量

// 白名单路由列表
const whiteList = [
  '/users/register',
  '/users/loginPw',
  '/users/loginCode',
  '/users/resetPassword',
  '/sms/sendCode'
];

export interface AuthRequest extends Request {
  user?: {
    id: number;
    phone: string;
  };
}

export const generateToken = (user: { id: number; phone: string }) => {
  return jwt.sign(
    {
      id: user.id,
      phone: user.phone
    },
    JWT_SECRET,
    { expiresIn: '24h' }
  );
};

export const verifyToken = (req: AuthRequest, res: Response, next: NextFunction) => {
  // 检查是否是白名单路由
  if (whiteList.includes(req.path)) {
    return next();
  }

  const token = req.headers['book-token'] as string;

  if (!token) {
    return res.status(401).json({ message: '未提供token' });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET) as { id: number; phone: string };
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ message: 'token无效或已过期' });
  }
};
